/**
 * Created by mac1 on 2017/11/14.
 */
var connect = require('connect');
connect()
  .use(logger)
  .use('/admin', restrict)
  .use('/admin', admin)
  .use(hello)
  .listen(3000);
function logger(req, res, next) {
  console.log('%s %s',req.method, req.url);
  next()
}
function fuck(req, res, next) {
 console.log('fuck admin');
 next();
}
function restrict(req, res, next) {
  var authorization = req.headers.authorization;
  console.log('authorizaiton '+authorization);
  if (!authorization) return next(new Error('Unauthorized'));
  var parts = authorization.split(' ');
  var scheme = parts[0];
  var auth = new Buffer(parts[1], 'base64').toString().split(':');
  var user = auth[0];
  var pass = auth[1];
  authenticateWithDatabase(user, pass, function (err) {
    if (err) return next(err);
    next();
  });
}
function authenticateWithDatabase(user, pass,errof) {
  console.log('user -> '+ user + ' pass -> ' + pass);
  errof();
}
function admin(req, res, next) {
  switch (req.url) {
    case '/':
      console.log('try admin /users');
      res.end('try /users');
      break;
    case '/users':
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify(['tobi', 'loki', 'jane']));
      break;
  }
  res.write('admin');
  next();
}
function hello(req, res, next) {
  res.end('hello');
}